package com.wry.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.wry.entity.Goods;
import com.wry.service.XxxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

/**
 * <h1>  <h1>
 *
 * @author 魏如元
 * @since 2022/10/19
 */
@Service
@Slf4j
public class XxxServiceImpl implements XxxService {

    @Override
    public void importXxx(HttpServletResponse response) throws IOException {
        String fileName = "tableWrite" + System.currentTimeMillis() + ".xlsx";
        // 方法1 这里直接写多个table的案例了，如果只有一个 也可以直一行代码搞定，参照其他案
        // 这里 需要指定写用哪个class去写
        //final ExcelWriterBuilder write = EasyExcel.write(fileName, Goods.class);

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/tmp.xlsx");
//        final ExcelWriter excelWriter = write.withTemplate(inputStream).build();
//        // 把sheet设置为不需要头 不然会输出sheet的头 这样看起来第一个table 就有2个头了
//        WriteSheet writeSheet = EasyExcel.writerSheet("模板").needHead(Boolean.FALSE).build();
//        // 这里必须指定需要头，table 会继承sheet的配置，sheet配置了不需要，table 默认也是不需要
//        WriteTable writeTable0 = EasyExcel.writerTable(0).needHead(Boolean.TRUE).build();
//        WriteTable writeTable1 = EasyExcel.writerTable(1).needHead(Boolean.TRUE).build();
//        // 第一次写入会创建头
//        excelWriter.write(Goods.createGoodsList(), writeSheet, writeTable0);
//        // 第二次写如也会创建头，然后在第一次的后面写入数据
//        excelWriter.write(Goods.createGoodsList(), writeSheet, writeTable1);
//        excelWriter.finish();
       // String templateFile = "D:\\wry_porject\\excel-import-and-export\\excel-import-easyexcel\\src\\main\\resources\\tmp.xlsx";

        String path = this.getClass().getClassLoader().getResource("template/tmp.xlsx").getFile();


        final HashMap<String, Object> data = new HashMap<>();
        data.put("orderNumber", "13213212");
        data.put("phone", "456465465");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setContentType("application/x-download");
        ServletOutputStream out = response.getOutputStream();

        final ExcelWriter excelWriter = EasyExcelFactory.write(out).withTemplate(path).build();
        final WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();

        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

        excelWriter.fill(data,fillConfig, writeSheet);
        excelWriter.fill(Goods.createGoodsList(),fillConfig, writeSheet);
        excelWriter.finish();
    }

}
